#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/29 21:36
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : view_sms_provider.py
# @Software: PyCharm
# @Desc    : SMSProvider视图（CRUD）
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework.generics import GenericAPIView

from common.utils.pagination import EnhancedPageNumberPagination
from common.utils.rsp import success_response, error_response
from ssms.filters.filter_sms_provider import SMSProviderFilter
from ssms.models import SMSProvider, SMSTemplate
from ssms.sers.ser_sms_provider import SMSProviderSerializer


class SMSProviderListCreateView(GenericAPIView):
    """
    SMSProvider列表查询 + 新增接口
    - GET: 分页查询短信供应商列表
    - POST: 新增短信供应商
    """
    queryset = SMSProvider.objects.filter(is_delete=0, pt_flag=0)
    serializer_class = SMSProviderSerializer
    pagination_class = EnhancedPageNumberPagination
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_class = SMSProviderFilter
    ordering_fields = ["create_time", "sort_num", "sms_name"]
    # 默认按排序号降序、创建时间降序排列
    ordering = ["-sort_num", "-create_time"]

    def get(self, request):
        """查询短信供应商列表"""
        filtered_qs = self.filter_queryset(self.get_queryset())
        page_qs = self.paginate_queryset(filtered_qs)
        serializer = self.get_serializer(page_qs, many=True)
        paginated_data = self.paginator.get_paginated_response(serializer.data).data
        return success_response(data=paginated_data, message="短信供应商列表查询成功")

    def post(self, request):
        """新增短信供应商"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return success_response(
            data=serializer.data,
            message=f"短信供应商「{serializer.validated_data['sms_name']}」创建成功"
        )


class SMSProviderRetrieveUpdateDestroyView(GenericAPIView):
    """
    SMSProvider单条操作接口
    - GET: 查询单个供应商详情
    - PUT/PATCH: 更新供应商
    - DELETE: 逻辑删除供应商
    """
    queryset = SMSProvider.objects.filter(is_delete=0,pt_flag=0).all()
    serializer_class = SMSProviderSerializer
    lookup_field = "pk"

    def get_object(self):
        """获取有效供应商（未删除+非压测）"""
        instance = super().get_object()
        if instance.is_delete == 1 or instance.pt_flag == 1:
            raise ValueError("短信供应商不存在或已被删除")
        return instance

    def get(self, request, pk):
        """查询单个供应商详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return success_response(data=serializer.data, message="短信供应商详情查询成功")

    def put(self, request, pk):
        """全量更新供应商"""
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=False)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return success_response(data=serializer.data, message=f"供应商「{instance.sms_name}」更新成功")

    def patch(self, request, pk):
        """部分更新供应商（如仅更新排序号、状态）"""
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return success_response(data=serializer.data, message=f"供应商「{instance.sms_name}」部分更新成功")

    def delete(self, request, pk):
        """逻辑删除供应商（检查是否关联模板）"""
        instance = self.get_object()
        # 检查是否有关联的短信模板
        if SMSTemplate.objects.filter(sms_provider=instance, is_delete=0).exists():
            return error_response(
                message=f"供应商「{instance.sms_name}」已关联短信模板，无法删除",
                code=400
            )
        # 执行逻辑删除
        instance.is_delete = 1
        instance.save()
        return success_response(data=None, message=f"供应商「{instance.sms_name}」已删除")
